package com.neusoft.neuiotms.common.repository.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.common.model.AuditLog;
import com.neusoft.neuiotms.common.model.QAuditLog;
import com.neusoft.neuiotms.common.repository.CustomizedAuditLogRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedAuditLogRepositoryImpl extends AbstractRepository
        implements CustomizedAuditLogRepository {

    @Override
    public Page<AuditLog> search(final Pageable pageable, final Searchable searchable) {
        final QAuditLog qQAuditLog = QAuditLog.auditLog;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<AuditLog> query = this.query().selectFrom(qQAuditLog);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return AuditLog.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QAuditLog qQAuditLog = QAuditLog.auditLog;
        if (!StringUtils.isEmpty(searchable.getStrValue("keyword"))) {
            where.or(super.containsStr(qQAuditLog.user, searchable, "keyword"));
            where.or(super.containsStr(qQAuditLog.opText, searchable, "keyword"));
            where.or(super.containsStr(qQAuditLog.opType, searchable, "keyword"));
            where.or(super.containsStr(qQAuditLog.remoteIp, searchable, "keyword"));
            where.or(super.containsStr(qQAuditLog.module, searchable, "keyword"));
        }

        return where;
    }
}
